package com.ruoyi.service;

import com.aliyun.dypnsapi20170525.Client;
import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.config.AliyunSmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SmsService {

    @Autowired
    private AliyunSmsConfig smsConfig;

    public SendSmsVerifyCodeResponse sendVerifyCode(String phoneNumber, String code, String minutes) throws Exception {
        Client client = createClient();
        String templateParam = String.format("{\"code\":\"%s\",\"min\":\"%s\"}", code, minutes);

        SendSmsVerifyCodeRequest request = new SendSmsVerifyCodeRequest()
                .setSignName(smsConfig.getSignName())
                .setTemplateCode(smsConfig.getTemplateCode())
                .setPhoneNumber(phoneNumber)
                .setTemplateParam(templateParam);

        RuntimeOptions runtime = new RuntimeOptions();
        return client.sendSmsVerifyCodeWithOptions(request, runtime);
    }

    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(smsConfig.getAccessKeyId())
                .setAccessKeySecret(smsConfig.getAccessKeySecret())
                .setEndpoint(smsConfig.getEndpoint());
        return new Client(config);
    }
}
